package com.xml.dom.write;

import java.io.File;
import java.io.FileWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class BookIDMain {

	private Document doc;

	/**
	 * Constructor
	 * 
	 * @param path
	 * @throws Exception
	 */
	public BookIDMain(String path) throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		doc = builder.parse(new File(path));
		this.editDocument();
	}

	/**
	 * ပြုပြင်ရေးသားခြင်း
	 */
	private void editDocument() {
		NodeList nodes = doc.getFirstChild().getChildNodes();
		int counter = 0;
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i);
			if (node instanceof Element) {
				Element book = (Element) node;
				book.setAttribute("id", String.valueOf(counter ++));
			}
		}
	}

	/**
	 * Document ကို ရယူခြင်း
	 * 
	 * @return
	 */
	public Document getDoc() {
		return this.doc;
	}

	/**
	 * XML ဖိုင်ကိုရေးသားခြင်း
	 * 
	 * @param name
	 *            အမည်
	 * @param doc
	 *            Document
	 * @throws Exception
	 * @throws TransformerFactoryConfigurationError
	 */
	public static void write(String name, Document doc) throws Exception,
			TransformerFactoryConfigurationError {
		Transformer trans = TransformerFactory.newInstance().newTransformer();
		trans.transform(new DOMSource(doc), new StreamResult(new FileWriter(
				name)));
	}

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		BookIDMain editor = new BookIDMain("book2.xml");
		Document doc = editor.getDoc();
		write("book3.xml",doc);
	}

}
